package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.mapper.*;
import com.woniu.domain.*;
import com.woniu.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.utils.Mysalt;
import com.woniu.vo.UserAndRole;
import org.apache.shiro.crypto.hash.Md5Hash;
import com.woniu.vo.UserAllInterviewsVo;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zyy
 * @since 2021-03-05
 */
@Service
//@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CollectMapper collectMapper;
    @Resource
    private FeedbackMapper feedbackMapper;
    @Resource
    private ResumeMapper resumeMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UserCompanyMapper userCompanyMapper;
    @Resource
    private UserPositionMapper userPositionMapper;

    @Resource
    private UserfeedbackMapper userfeedbackMapper;

    @Override
    public Set<Permission> getOneTwoMenus(Integer uid) {
        List <Permission> permissions=userMapper.getMenus(uid);
        Set<Permission> needPermissions=new LinkedHashSet<>();
        permissions.forEach(permission -> {
            if(permission.getLevel()==1){
                needPermissions.add(permission);
                permission.setChildren(new LinkedHashSet<Permission>());
            }
        });
        permissions.forEach(permission -> {
            needPermissions.forEach(first->{
                if(permission.getPid()==first.getId()){
                    first.getChildren().add(permission);
                }
            });
        });
        return needPermissions;
    }

    @Override
    public boolean deleteUserById(Integer uid) {
        int i = userMapper.deleteById(uid);

        QueryWrapper<Collect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",uid);
        collectMapper.delete(wrapper);

        QueryWrapper<Userfeedback> wrapper1 = new QueryWrapper<>();
        wrapper.eq("uid",uid);
        userfeedbackMapper.delete(wrapper1);

        QueryWrapper<Feedback> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("user_id",uid);
        feedbackMapper.delete(wrapper2);

        QueryWrapper<Resume> wrapper3 = new QueryWrapper<>();
        wrapper3.eq("uid",uid);
        resumeMapper.delete(wrapper3);

        QueryWrapper<UserRole> wrapper4 = new QueryWrapper<>();
        wrapper4.eq("uid",uid);
        userRoleMapper.delete(wrapper4);

        return true;
    }

    @Override
    public void deleteCompanyUserById(Integer uid) {
        userMapper.deleteById(uid);

        QueryWrapper<UserCompany> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id",uid);
        userCompanyMapper.delete(queryWrapper1);

        QueryWrapper<UserPosition> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("uid",uid);
        userPositionMapper.delete(queryWrapper2);

        QueryWrapper<UserRole> wrapper4 = new QueryWrapper<>();
        wrapper4.eq("uid",uid);
        userRoleMapper.delete(wrapper4);

    }


    //用户注册，返回用户id
    @Override
    public Integer userRegister(UserAndRole userAndRole) {
        String salt = Mysalt.getSalt(8);
        Md5Hash md5Hash = new Md5Hash(userAndRole.getPassword(),salt,1024);
        String newPassword = md5Hash.toHex();
        User user = new User();
        user.setPassword(newPassword);
        user.setSalt(salt);
        user.setUsername(userAndRole.getUsername());
        user.setTel(userAndRole.getTel());
        user.setStatus("正常");
        userMapper.insert(user);
        userMapper.setRoleByUid(user.getId(),userAndRole.getRid());
        return user.getId();
    }


    //    求职者面试情况
//   1.1 全部面试
    @Override
    public List<UserAllInterviewsVo> interviewManagementData(Integer userId) {


        ListOperations listOperations = redisTemplate.opsForList();
        List range = listOperations.range("userId:" + userId+"全部面试", 0, -1);


        if (ObjectUtils.isEmpty(range)) {
            synchronized (this) {
                List ranges = listOperations.range("userId:" + userId+"全部面试", 0, -1);
                if (ObjectUtils.isEmpty(ranges)) {
//                    数据库查询
                    List<UserAllInterviewsVo> allInterviews = userMapper.interviewManagementData(userId);

                    if (ObjectUtils.isEmpty(allInterviews)) {
                        System.out.println("查询为空");
                        return null;
                    }
                    listOperations.leftPushAll("userId:" + userId+"全部面试", allInterviews);
                    redisTemplate.expire("userId:" + userId+"全部面试",10, TimeUnit.MINUTES);
                    System.out.println("走了数据库查询");
                    return allInterviews;
                }
            }
        }
        redisTemplate.expire("userId:" + userId+"全部面试",2, TimeUnit.MINUTES);
        System.out.println("走了redis查询");
        return range;

    }


    //    1.2 已接受面试
    @Override
    public List<UserAllInterviewsVo> accepted(Integer userId) {
        ListOperations listOperations = redisTemplate.opsForList();
        List range = listOperations.range("userId:" + userId+"已接受面试", 0, -1);
        if (ObjectUtils.isEmpty(range)) {
            synchronized (this) {
                List ranges = listOperations.range("userId:" + userId+"已接受面试", 0, -1);
                if (ObjectUtils.isEmpty(ranges)) {
//                    数据库查询
                    List<UserAllInterviewsVo> accepted = userMapper.accepted(userId);
                    if (ObjectUtils.isEmpty(accepted)) {
                        System.out.println("查询为空");
                        return null;
                    }
                    redisTemplate.expire("userId:" + userId+"已接受面试",2, TimeUnit.MINUTES);
                    listOperations.leftPushAll("userId:" + userId+"已接受面试", accepted);
                    System.out.println("走了数据库查询");
                    return accepted;
                }
            }
        }
        redisTemplate.expire("userId:" + userId+"已接受面试",2, TimeUnit.MINUTES);
        System.out.println("走了redis查询");
        return range;


    }

//    1.3待处理

    @Override
    public List<UserAllInterviewsVo> pendingProcessing(Integer userId) {
        ListOperations listOperations = redisTemplate.opsForList();
        List range = listOperations.range("userId:" + userId+"待处理面试", 0, -1);
        if (ObjectUtils.isEmpty(range)) {
            synchronized (this) {
                List ranges = listOperations.range("userId:" + userId+"待处理面试", 0, -1);
                if (ObjectUtils.isEmpty(ranges)) {
//                    数据库查询
                    List<UserAllInterviewsVo> pendingProcessing = userMapper.pendingProcessing(userId);
                    if (ObjectUtils.isEmpty(pendingProcessing)) {
                        System.out.println("查询为空");
                        return null;
                    }

                    redisTemplate.expire("userId:" + userId+"待处理面试",2, TimeUnit.MINUTES);
                    listOperations.leftPushAll("userId:" + userId+"待处理面试", pendingProcessing);

                    System.out.println("走了数据库查询");
                    return pendingProcessing;
                }
            }
        }
        redisTemplate.expire("userId:" + userId+"待处理面试",2, TimeUnit.MINUTES);
        System.out.println("走了redis查询");
        return range;


    }

    //    1.4已拒绝
    @Override
    public List<UserAllInterviewsVo> hasBeenRejected(Integer userId) {

        ListOperations listOperations = redisTemplate.opsForList();
        List range = listOperations.range("userId:" + userId+"已拒绝", 0, -1);
        if (ObjectUtils.isEmpty(range)) {
            synchronized (this) {
                List ranges = listOperations.range("userId:" + userId+"已拒绝", 0, -1);
                if (ObjectUtils.isEmpty(ranges)) {
//                    数据库查询
                    List<UserAllInterviewsVo> hasBeenRejected = userMapper.hasBeenRejected(userId);
                    if (ObjectUtils.isEmpty(hasBeenRejected)) {
                        System.out.println("查询为空");
                        return null;
                    }

                    redisTemplate.expire("userId:" + userId+"已拒绝",2, TimeUnit.MINUTES);
                    listOperations.leftPushAll("userId:" + userId+"已拒绝", hasBeenRejected);
                    System.out.println("走了数据库查询");
                    return hasBeenRejected;
                }
            }
        }
        redisTemplate.expire("userId:" + userId+"已拒绝",2, TimeUnit.MINUTES);
        System.out.println("走了redis查询");
        return range;


//        List<UserAllInterviewsVo> hasBeenRejected = userMapper.hasBeenRejected(userId);
//        if (ObjectUtils.isEmpty(hasBeenRejected)) {
//            System.out.println("查询为空");
//            return null;
//        }
//        return hasBeenRejected;
    }


    //    2我的申请
//    2.1 已申请
    @Override
    public List<UserAllInterviewsVo> hasApplied(Integer userId) {
        ListOperations listOperations = redisTemplate.opsForList();
        List range = listOperations.range("userId:" + userId+"已申请", 0, -1);
        if (ObjectUtils.isEmpty(range)) {
            synchronized (this) {
                List ranges = listOperations.range("userId:" + userId+"已申请", 0, -1);
                if (ObjectUtils.isEmpty(ranges)) {
//                    数据库查询
                    List<UserAllInterviewsVo> hasApplied = userMapper.hasApplied(userId);
                    if (ObjectUtils.isEmpty(hasApplied)) {
                        System.out.println("查询为空");
                        return null;
                    }
                    redisTemplate.expire("userId:" + userId+"已申请",2, TimeUnit.MINUTES);
                    listOperations.leftPushAll("userId:" + userId+"已申请", hasApplied);
                    System.out.println("走了数据库查询");
                    return hasApplied;
                }
            }
        }
        redisTemplate.expire("userId:" + userId+"已申请",2, TimeUnit.MINUTES);
        System.out.println("走了redis查询");
        return range;


//        List<UserAllInterviewsVo> hasApplied = userMapper.hasApplied(userId);
//        if (ObjectUtils.isEmpty(hasApplied)) {
//            System.out.println("查询为空");
//            return null;
//        }
//        return hasApplied;
    }


    //2.我的申请
//    2.2 我的收藏

    @Override
    public List<UserAllInterviewsVo> myCollection(Integer userId) {
//        ListOperations listOperations = redisTemplate.opsForList();
//        List range = listOperations.range("userId:" + userId+"我的收藏", 0, -1);
//        if (ObjectUtils.isEmpty(range)) {
//            synchronized (this) {
//                List ranges = listOperations.range("userId:" + userId+"我的收藏", 0, -1);
//                if (ObjectUtils.isEmpty(ranges)) {
////                    数据库查询
//                    List<UserAllInterviewsVo> myCollection = userMapper.myCollection(userId);
//
//                    if (ObjectUtils.isEmpty(myCollection)) {
//                        System.out.println("查询为空");
//                        return null;
//                    }
//                    redisTemplate.expire("userId:" + userId+"我的收藏",10, TimeUnit.MINUTES);
//                    listOperations.leftPushAll("userId:" + userId+"我的收藏", myCollection);
//                    System.out.println("走了数据库查询");
//                    return myCollection;
//                }
//            }
//        }
//        redisTemplate.expire("userId:" + userId+"我的收藏",10, TimeUnit.MILLISECONDS);
//        System.out.println("走了redis查询");
//        return range;

        List<UserAllInterviewsVo> myCollection = userMapper.myCollection(userId);

        if (ObjectUtils.isEmpty(myCollection)) {
            System.out.println("查询为空");
            return null;
        }
        return myCollection;
    }

    //    我的收藏新增功能
    @Override
    public int insertCollection(Integer companyId, Integer positionId, Integer userId) {
        int i = userMapper.insertCollection(companyId, positionId, userId);
        if (i<0) {
            return 0;
        }
        return 1;
    }

    //    支付宝修改用户类型
    @Override
    public void vip(Integer uid) {
         userMapper.vip(uid);

    }
}
